<template>
  <div>
    <a-modal
      centered
      :title="title"
      :width="1000"
      :visible="visible"
      @ok="handleOk"
      @cancel="handleCancel"
      cancelText="关闭">

      <a-spin :spinning="confirmLoading">
        <j-form-container>
          <a-form-model ref="form" :model="model" slot="detail">
            <a-row>
              <a-col :span="24">
                <a-form-model-item label="施工节点" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="progressId">
                  <a-tree-select
                    v-model="model.progress"
                    :label-in-value="true"
                    style="width: 100%"
                    :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                    :tree-data="treeData"
                    placeholder="请选择施工节点"
                    @change="changeConstruction"
                    tree-default-expand-all
                  >

                  </a-tree-select>
                </a-form-model-item>
              </a-col>
              <a-col :span="24" v-show="showProgressFlag">
                <a-form-model-item label="施工进度" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="content">
                  <div style="border: 1px solid lightgrey;border-radius: 5px">
                    <span style="margin-left: 15px">完成进度：{{showProgressValue}}%</span>
                    <van-slider 
                        v-model="showProgressValue" 
                        button-size="18"
                        style="width: 92%;margin: 20px auto;"  />
                  </div>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="施工日志内容" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="content">
                  <a-textarea
                    v-model="model.content"
                    placeholder="请输入施工日志内容"
                    :auto-size="{ minRows: 3, maxRows: 5 }"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="日志图片" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="progressId">
                  <div class="clearfix">
                    <a-upload
                      :action="uploadAction"
                      list-type="picture-card"
                      :beforeUpload="doBeforeUpload"
                      :file-list="fileList"
                      :headers="headers"
                      :data="{'biz':'temp'}"
                      :returnUrl="returnUrl"
                      @preview="handlePreview"
                      @change="handleChange"
                    >
                      <div v-if="fileList.length < 8">
                        <a-icon type="plus"/>
                        <div class="ant-upload-text">
                          上传
                        </div>
                      </div>
                    </a-upload>
                    <a-modal :visible="previewVisible" :footer="null" @cancel="handleClose">
                      <img alt="example" style="width: 100%" :src="previewImage"/>
                    </a-modal>
                  </div>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="是否对业主可见" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="content">
                  <a-radio-group :default-value="0" v-model="model.isShow" button-style="solid">
                    <a-radio-button value="1">
                      可见
                    </a-radio-button>
                    <a-radio-button value="0">
                      不可见
                    </a-radio-button>
                  </a-radio-group>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-form-model>
        </j-form-container>
      </a-spin>
    </a-modal>
  </div>
</template>

<script>

  import Vue from "vue";
  import {ACCESS_TOKEN} from "@/store/mutation-types"
  import {getFileAccessHttpUrl} from '@/api/manage'
  import {getAction, postAction} from "@api/manage";

  const FILE_TYPE_IMG = "image"
  const FILE_TYPE_ALL = "all"

  const uidGenerator = () => {
    return '-' + parseInt(Math.random() * 10000 + 1, 10);
  }
  const getFileName = (path) => {
    if (path.lastIndexOf("\\") >= 0) {
      let reg = new RegExp("\\\\", "g");
      path = path.replace(reg, "/");
    }
    return path.substring(path.lastIndexOf("/") + 1);
  }

  function getBase64(file) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result);
      reader.onerror = error => reject(error);
    });
  }

  export default {
    name: "LogAdd",
    data() {
      return {
        treeData: [],
        showProgressFlag: false,
        showProgressValue: 0,
        uploadAction: window._CONFIG['domianURL'] + "/sys/oss/file/upload",
        headers: {},
        title: '',
        fileList: [],
        newFileList: [],
        previewVisible: false,
        previewImage: '',
        width: 800,
        visible: false,
        customerId: 0,
        phone: '',
        model: {},
        confirmLoading: false,
        labelCol: {
          xs: {span: 24},
          sm: {span: 5},
        },
        wrapperCol: {
          xs: {span: 24},
          sm: {span: 16},
        },
        url: {
          logAdd: "/ghConstructLog/add",
          treeList: "/ghCustomerProgress/treeList"
        },
        value: {
          type: [String, Array],
          required: false
        },
        returnUrl: {
          type: Boolean,
          required: false,
          default: true
        },
        bizPath: {
          type: String,
          required: false,
          default: "temp"
        },
        uploadGoOn:true,
        fileSizeArr: [],
        fileType:{
          type:String,
          required:false,
          default:FILE_TYPE_ALL
        },
        beforeUpload: {
          type: Function
        },
      }
    },
    created() {
      const token = Vue.ls.get(ACCESS_TOKEN);
      this.headers = {"X-Access-Token": token}
    },
    computed: {
      formDisabled() {
        return this.disabled
      },
    },
    methods: {
      changeConstruction(val) {
        this.showProgressFlag = true;
        this.showProgressValue = val.value;
        for (let i = 0; i < this.treeData.length; i++) {
          if (val.value == this.treeData[i].id) {
            this.showProgressValue = this.treeData[i].rate;
            break;
          } else {
            for (let j = 0; j < this.treeData[i].children.length; j++) {
              if (val.value == this.treeData[i].children[j].id) {
                this.showProgressValue = this.treeData[i].children[j].rate;
                break;
              }
            }
          }
        }
      },
      add(customerId) {
        this.visible = true
        this.customerId = customerId;
        this.initTreeData(customerId);
      },
      close() {
        this.$emit('close');
        this.visible = false;
        this.model = {};
        this.showProgressValue = 0;
        this.fileList = [];
      },
      initTreeData(customerId) {
        getAction(this.url.treeList, {customerId: customerId}).then((res) => {
          if (res.success) {
            this.treeData = res.result.records || res.result;
          } else {
            this.$message.warning(res.message)
          }
        })
      },
      async handlePreview(file) {
        if (!file.response.result && !file.preview) {
          file.preview = await getBase64(file.originFileObj);
        }
        this.previewImage = file.response.result || file.preview;
        this.previewVisible = true;
      },

      doBeforeUpload(file){
        var fileType = file.type;
        if (fileType.indexOf('image')<0){
          this.$message.warning('请上传图片');
          this.uploadGoOn=false
          return false;
        }
        const isLt10M = file.size / 1024 / 1024 < 10
        if (!isLt10M) {
          this.$message.error('上传文件大小不能超过 10MB!')
          this.uploadGoOn=false
          return false;
        }
        return true;
      },

      handleChange(info) {
        console.log("--文件列表改变--")
        if (!info.file.status && this.uploadGoOn === false) {
          info.fileList.pop();
        }
        let fileList = info.fileList
        if (info.file.status === 'done') {
          if (this.number > 0) {
            fileList = fileList.slice(-this.number);
          }
          if (info.file.response.success) {
            fileList = fileList.map((file) => {
              if (file.response) {
                // let reUrl = file.response.message;
                // file.url = getFileAccessHttpUrl(reUrl);
                file.url = file.response.result;
              }
              return file;
            });
          }
          //this.$message.success(`${info.file.name} 上传成功!`);
        } else if (info.file.status === 'error') {
          this.$message.error(`${info.file.name} 上传失败.`);
        } else if (info.file.status === 'removed') {
          this.handleDelete(info.file)
        }
        this.fileList = fileList
        if (info.file.status === 'done' || info.file.status === 'removed') {
          //returnUrl为true时仅返回文件路径
          if (this.returnUrl) {
            this.handlePathChange()
          } else {
            //returnUrl为false时返回文件名称、文件路径及文件大小
            this.newFileList = [];
            for (var a = 0; a < fileList.length; a++) {
              // update-begin-author:lvdandan date:20200603 for:【TESTA-514】【开源issue】多个文件同时上传时，控制台报错
              if (fileList[a].status === 'done') {
                var fileJson = {
                  fileName: fileList[a].name,
                  filePath: fileList[a].response.message,
                  fileSize: fileList[a].size
                };
                this.newFileList.push(fileJson);
              } else {
                return;
              }
              // update-end-author:lvdandan date:20200603 for:【TESTA-514】【开源issue】多个文件同时上传时，控制台报错
            }
            this.$emit('change', this.newFileList);
          }
        }
      },
      handlePathChange() {
        let uploadFiles = this.fileList
        let path = ''
        if (!uploadFiles || uploadFiles.length == 0) {
          path = ''
        }
        let arr = [];
        if (!this.isMultiple && uploadFiles.length > 0) {
          arr.push(uploadFiles[uploadFiles.length - 1].response.message)
        } else {
          for (let a = 0; a < uploadFiles.length; a++) {
            // update-begin-author:taoyan date:20200819 for:【开源问题z】上传图片组件 LOWCOD-783
            if (uploadFiles[a].status === 'done') {
              arr.push(uploadFiles[a].response.message)
            } else {
              return;
            }
            // update-end-author:taoyan date:20200819 for:【开源问题z】上传图片组件 LOWCOD-783
          }
        }
        if (arr.length > 0) {
          path = arr.join(",")
        }
        this.$emit('change', path);
      },

      handleOk() {
        const that = this;
        // 触发表单验证
        //that.confirmLoading = true;

        if (that.model.progress == null || that.model.progress == ""){
          that.$message.error("请选择施工节点")
          return;
        }
        if (that.model.content == null || that.model.content == ""){
          that.$message.error("施工日志内容不能为空")
          return;
        }
        if (that.model.isShow == null || that.model.isShow === ""){
          that.$message.error("请选择对业主是否可见")
          return;
        }
        let images = "";
        for (let i = 0; i < this.fileList.length; i++) {
          images += this.fileList[i].url + ",";
        }
        that.model.progressId = that.model.progress.value
        that.model.images = images;
        that.model.customerId = that.customerId;
        that.model.phone = that.phone;
        that.model.rate = that.showProgressValue;
        postAction(that.url.logAdd, that.model).then((res) => {
          if (res.success) {
            that.$message.success(res.message);
            that.$emit('ok');
          } else {
            that.$message.warning(res.message);
          }
        }).finally(() => {
          that.confirmLoading = false;
          this.close()
        })
      },
      submitCallback() {
        this.$emit('ok');
        this.visible = false;
      },
      //关闭预览照片
      handleClose() {
        this.previewVisible = false;
      },
      handleCancel() {
        this.close()
      },
      //删除图片
      handleDelete(file){
        console.log("=========="+file)
      }
    }
  }
</script>

<style scoped>
  .ant-upload-select-picture-card i {
    font-size: 32px;
    color: #999;
  }

  .ant-upload-select-picture-card .ant-upload-text {
    margin-top: 8px;
    color: #666;
  }
</style>